<?php

namespace App\Models;

use App\Http\Util\SRedis;
use App\Http\Util\TimeZoneTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*
 *  设备表
 * */

class Device extends Model
{


    //时区自动转化
    use TimeZoneTrait;

    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id', 'id');
    }


    //table name
    protected $table = 'device';

    //csv的key的数组
    static $_csvKeyArr = ['二维码编号','表号', '主题(IMEI)', '物联网卡号', '蓝牙Mac地址'];

    static $_csvMap = [
        '表号' => 'name',
        '蓝牙Mac地址' => 'mac',
        '主题(IMEI)' => 'module_no',
        '物联网卡号' => 'iccid',
        '二维码编号' => 'sn'
    ];

    /*
     * 增加设备的使用次数
     */
    public static function addUseCount($mac)
    {
        //查询设备的用户id
        $userId = self::where('mac', $mac)->value('user_id');
        $redis = new SRedis();
        $recordMonth = $redis->get('call_counts_month_key_'. $userId);
        //获到当前月份
        $monthNow = date('Y-m');
        if($recordMonth!=$monthNow){
            $redis->set('user_call_counts_month_key_'. $userId, $monthNow);
            //增加设备表的总使用次数和月使用次数
            self::where('mac', $mac)->update([
                'call_count' => DB::raw('call_count + 1'),
                'call_count_month' => 1
            ]);

            //增加用户的调用次数
            User::where('id', $userId)->update([
                'call_count_used' => DB::raw('call_count_used + 1'),
                'call_count_used_month' => 1
            ]);

        }else{
            //增加设备表的总使用次数和月使用次数

            self::where('mac', $mac)->update([
                'call_count_used' => DB::raw('call_count_used + 1'),
                'call_count_used_month' => DB::raw('call_count_used_month + 1')
            ]);
            User::where('id', $userId)->update([
                'call_count' => DB::raw('call_count + 1'),
                'call_count_month' => DB::raw('call_count_month + 1')
            ]);
        }

        UserCallCountsDaily::addUseCount($userId);
        DeviceCallCountsDaily::addUseCount($mac);
        return true;

    }


}
